/**
 * my service
 */
const lodash = require('lodash');
let ErrorUtils = require('../utils/error/ErrorUtils');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');
const config = require('../config');
const redis = require('../redis');
let emailCodeKey = 'email-code-key';
const emailServer = require("../email");

class EmailService {

    static checkEmailValiData(data) {
        let schema = Joi.object({
            email: Joi.string().min(3).max(30).required(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     * 发送邮件
     */
    static async sendEmailCode(data) {
        //infoLogger.info("邮箱信息",emailServer);
        //核验邮箱验证码
        await  EmailService.checkEmailValiData(data);
        let code = lodash.random(100000, 999999);
        return new Promise(function (resolve, reject) {
            emailServer().sendMail({
                    from: config.email.user,
                    to: data.email,
                    subject: '学历学位身份认证',
                    html: `你正在使用邮箱进行学历学位认证，验证码是（${code}），该验证码15分钟内有效。【全球学历学位认证中心】`
                }, function (error, response) {
                    if (error) {
                        console.log(error);
                        resolve(error);
                        return;
                    }
                    console.log('发送成功');
                    //设置code 到redis
                    EmailService.setEmailValue(data.email, code);
                    resolve(response);
                }
            );
        });
    }

    static setEmailValue(email, code) {
        if (!email) {
            return Promise.reject(null);
        }
        let key = `${emailCodeKey}:${email}`;
        return redis.setex(key, 7200, code);
    };

    /**
     * 获取邮箱的验证码值
     */
    static getEmailValue(email) {
        if (!email) {
            return Promise.reject(null);
        }
        let key = `${emailCodeKey}:${email}`;

        return redis.get(key);
    };

    /**
     * 删除邮箱的验证码值
     */
    static delEmailValue(email) {
        if (!email) {
            return Promise.reject(null);
        }
        let key = `${emailCodeKey}:${email}`;

        return redis.del(key);
    };

    /**
     * 校验邮箱验证码
     */
    static async checkEmailCode(email, code) {
        let redisCode = await EmailService.getEmailValue(email);
        if (!code) {
            ErrorUtils.throwApiError(ErrorUtils.EMAIL_VERIFY_CODE_NOT_EXISTS);
        }
        if (code == redisCode) {
            return true;
        } else {
            ErrorUtils.throwApiError(ErrorUtils.EMAIL_VERIFY_CODE_ERROR);
        }
    }
}

module.exports = EmailService;